<?php

require_once APPPATH."/controllers/BasePriv.php";
require_once APPPATH."/libraries/Tools.php";
require APPPATH."/libraries/FFmpeg.php";
use Aws\S3\S3Client;
class Material extends BasePriv
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', "url"));
        $this->load->model("Host_user_material_model", "table");
        $this->user_material="user_material";
        $this->detail_msg="detail_msg";//操作详细表
    }

    /**
     * 待审核
     */
    public function index(){
        //分页
        $arr=[];
        $arr['page']=intval($this->get('page'))>0 ? intval($this->get('page')) : 1;
        $arr['limit']=intval($this->get('limit'))>0 ? intval($this->get('limit')) : 10;
        $arr['type']=2;
        //分类筛选
        if(!empty($_GET['join_type'])){
            $arr['join_type']=$_GET['join_type'];
        }
        //话题筛选
        if(!empty($_GET['join_type_sub'])){
            $arr['join_type_sub']=$_GET['join_type_sub'];
        }
        //时间搜索
        if(!empty($_GET['time'])) {
            $get_time=$this->getStartAndEndTime("get");
            $start_time=strtotime($get_time[0]);
            $end_times=strtotime($get_time[1]);
            $end_time=$end_times+86400;
            $start=date("Y-m-d H:i:s",$start_time);
            $end=date("Y-m-d H:i:s",$end_time);
            $arr['start_time'] =$start;
            $arr['end_time'] =$end;
        }
        //配音与视频筛选
        if(!empty($_GET['video_type'])){
            if($_GET['video_type']!=3){
                $arr['video_type']=$_GET['video_type'];
            }
            $data['video_type']=$_GET['video_type'];
        }

        $res=$this->table->all($arr);
        //查询分类
        $type=$this->table->types(1);
        //查询话题
        $type_sub=$this->table->type_sub("",2);
        //显示话题和分类
        if(!empty($res['row'])){
            foreach($res['row'] as $k=>&$v){
//                foreach($type as $kk=>$vv){
//                    if($v['quality_join_type']==$vv['id']){
//                        $v['quality_join_type_name']=$vv['name'];
//                    }
//                }
                foreach($type_sub as $kkk=>$vvv){
                    if($v['join_type_sub']==$vvv['id']){
                        $v['join_type_sub_name']=$vvv['sub_title'];
                    }
                }
            }
        }
        $data['data']=$res;
        $data['html_type']=2;
        $data['type_sub']=$this->table->type_sub("",2);
        $data['types']=$type;
        $data['page']=$arr['page'];
        $data['limit']=$arr['limit'];
        $this->layout("user_material/user_material/index",$data);
    }

    /**
     * 审核通过
     */
    public function pass(){
        //分页
        $arr=[];
        $arr['page']=intval($this->get('page'))>0 ? intval($this->get('page')) : 1;
        $arr['limit']=intval($this->get('limit'))>0 ? intval($this->get('limit')) : 10;
        $arr['type']=3;
        //分类筛选
        if(!empty($_GET['join_type'])){
            $arr['join_type']=$_GET['join_type'];
        }
        //话题筛选
        if(!empty($_GET['join_type_sub'])){
            $arr['join_type_sub']=$_GET['join_type_sub'];
        }
        //时间搜索
        if(!empty($_GET['time'])) {
            $get_time=$this->getStartAndEndTime("get");
            $start_time=strtotime($get_time[0]);
            $end_times=strtotime($get_time[1]);
            $end_time=$end_times+86400;
            $start=date("Y-m-d H:i:s",$start_time);
            $end=date("Y-m-d H:i:s",$end_time);
            $arr['start_time'] =$start;
            $arr['end_time'] =$end;
        }

        //配音与视频筛选
        if(!empty($_GET['video_type'])){
            if($_GET['video_type']!=3){
                $arr['video_type']=$_GET['video_type'];
            }
            $data['video_type']=$_GET['video_type'];
        }

        $res=$this->table->all($arr);
        //查询分类
        $type=$this->table->types(1);
        //查询话题
        $type_sub=$this->table->type_sub("",2);
        //显示话题和分类
        if(!empty($res['row'])){
            foreach($res['row'] as $k=>&$v){
//                foreach($type as $kk=>$vv){
//                    if($v['join_type']==$vv['id']){
//                        $v['join_type_name']=$vv['name'];
//                    }
//                }
                foreach($type_sub as $kkk=>$vvv){
                    if($v['join_type_sub']==$vvv['id']){
                        $v['join_type_sub_name']=$vvv['sub_title'];
                    }
                }
            }
        }
        $data['data']=$res;
        $data['html_type']=3;
        $data['types']=$type;
        $data['type_sub']=$this->table->type_sub("",2);
        $data['page']=$arr['page'];
        $data['limit']=$arr['limit'];
        $this->layout("user_material/user_material/pass",$data);
    }

    /**
     * 审核未通过
     */
    public function no_pass(){
        //分页
        $arr=[];
        $arr['page']=intval($this->get('page'))>0 ? intval($this->get('page')) : 1;
        $arr['limit']=intval($this->get('limit'))>0 ? intval($this->get('limit')) : 10;
        $arr['type']=1;
        //分类筛选
        if(!empty($_GET['join_type'])){
            $arr['join_type']=$_GET['join_type'];
        }
        //话题筛选
        if(!empty($_GET['join_type_sub'])){
            $arr['join_type_sub']=$_GET['join_type_sub'];
        }
        //时间搜索
        if(!empty($_GET['time'])) {
            $get_time=$this->getStartAndEndTime("get");
            $start_time=strtotime($get_time[0]);
            $end_times=strtotime($get_time[1]);
            $end_time=$end_times+86400;
            $start=date("Y-m-d H:i:s",$start_time);
            $end=date("Y-m-d H:i:s",$end_time);
            $arr['start_time'] =$start;
            $arr['end_time'] =$end;
        }
        //配音与视频筛选
        if(!empty($_GET['video_type'])){
            if($_GET['video_type']!=3){
                $arr['video_type']=$_GET['video_type'];
            }
            $data['video_type']=$_GET['video_type'];
        }


        $res=$this->table->all($arr);
        //查询分类
        $type=$this->table->types(1);
        //查询话题
        $type_sub=$this->table->type_sub("",3);
        //显示话题和分类
        if(!empty($res['row'])){
            foreach($res['row'] as $k=>&$v){
//                foreach($type as $kk=>$vv){
//                    if($v['quality_join_type']==$vv['id']){
//                        $v['quality_join_type_name']=$vv['name'];
//                    }
//                }
                foreach($type_sub as $kkk=>$vvv){
                    if($v['join_type_sub']==$vvv['id']){
                        $v['join_type_sub_name']=$vvv['sub_title'];

                    }
                }
            }
        }
        $data['data']=$res;
        $data['html_type']=1;
        $data['types']=$type;
        $data['type_sub']=$this->table->type_sub("",2);
        $data['page']=$arr['page'];
        $data['limit']=$arr['limit'];
        $this->layout("user_material/user_material/no_pass",$data);
    }

    /**
     * 通过
     */
    public function join(){
        $id=$_REQUEST['id'];
        if(empty($id)){
            response(-1,"缺少参数");
        }
        $user_score=$_POST['user_score'];
        if(!is_numeric($_POST['user_score'])){
            response(-1, "得分值不是数字");
        }
        if($_POST['user_score']>5 || $_POST['user_score'] <1){
            response(-1, "得分值不合理");
        }
        $data['examine']=3;
        $data['user_score']=$_POST['user_score'];
        $res=$this->table->update("user_material",$data,["id"=>$id]);
        if($res){
            //推送给未来电视,test（测试），product（正式）
            $re=$this->table->push($id,"test");
            response(0,"通过成功");
        }else {
            response(-1,"通过失败");
        }
    }

    /**
     * 通过
     */
    public function drop_join(){
        $id=$_POST['id'];
        if(empty($id)){
            response(-1,"缺少参数");
        }
        $user_score=$_POST['user_score'];
        if(!is_numeric($_POST['user_score'])){
            response(-1, "得分值不是数字");
        }
        if($_POST['user_score']>5 || $_POST['user_score'] <1){
            response(-1, "得分值不合理");
        }
        $data['examine']=3;
        $data['user_score']=$_POST['user_score'];
        $res=$this->table->update("user_material",$data,["id"=>$id]);
        if($res){
            //推送给未来电视,test（测试），product（正式）
            response(0,"通过成功");
        }else {
            response(-1,"通过失败");
        }
    }

    /**
     * 弃用
     */
    public function drop(){
        $id=$_POST['id'];
        if(empty($id)){
            response(-1,"缺少参数");
        }
        //先去查询这个数据是用户上传还是后台上传
        $user_material=$this->table->one($this->user_material,['id'=>$id]);
        if($user_material['is_user_zj']==2){
            //如果是用户上传，先改变这个user_material表为弃用，再去改变精品视频表为弃用
            $data2['online']=1;
            $data1['examine']=1;
            $res=$this->table->update_quality_user($data1,$data2,$id);
        }else if($user_material['is_user_zj']==1){
            //如果是用户上传，直接把这条变为弃用就行
            $data['examine']=1;
            $res=$this->table->update("user_material",$data,["id"=>$id]);
        }

        if($res){
            response(0,"弃用成功");
        }else {
            response(-1,"弃用失败");
        }
    }

    /**
     * 删除
     */
    public function del(){
        $id=$_POST['id'];
        if(empty($id)){
            response(-1,"缺少参数");
        }
        //先去查询精品表是否有这个视频
        $res=$this->table->del($id);
        if($res){
            //拼接数据入库
            $data['user_id']=$this->userInfo['role_id'];
            $data['user_name']=$this->userInfo['name'];
            $data['detail_msg']=json_encode($res);
            $data['add_time']=date("Y-m-d H:i:s",time());
            $this->table->add($this->detail_msg,$data);
            response(0,"删除成功");
        }else {
            response(-1,"删除失败");
        }
    }

    /**
     * 评分修改
     */
    public function update_pingfen(){
        $id=$_POST['id'];
        $pingfen=$_POST['pingfen'];
        if(empty($id) || empty($pingfen)){
            response(-1,"缺少参数");
        }
        if(!is_numeric($pingfen)){
            response(-1,"请填写数字");
        }
        if($pingfen <0 || $pingfen >5){
            response(-1,"评分在1-5之间");
        }
        //先去查询精品表是否有这个视频
        $res=$this->table->update($this->user_material,['user_score'=>$pingfen],['id'=>$id]);
        if($res){
            response(0,"修改成功");
        }else {
            response(-1,"修改失败");
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $video_uuid=$_REQUEST['video_uuid'];
        if(empty($video_uuid)){
            response(-1,"缺少参数");
        }
        $res=$this->table->one("user_material",["id"=>$video_uuid]);
        $data['data']=$res;
        $data['type']=$this->table->types();
        $data['type_sub']=$this->table->type_sub(['sub_type'=>$res['join_type']]);
        $this->layout("user_material/user_material/edit",$data);
    }

    /**
     * 保存编辑
     */
    public function save_edit(){
        //验证参数
        if(empty($_POST['fenlei'])){
            response(-1,"请选择分类");
        }
        if(empty($_POST['huati'])){
            response(-1,"请选择话题");
        }
        if(empty($_POST['video_url2'])){
            response(-1,"封面不能为空");
        }
////////////////////////////////////////////////////////////////////////////裁剪视频开始/////////////////////////////////////////////////////////////////////////////////////
        //这是视频裁剪只传一组数据的，
        if(empty($_POST['update_video'][0][0]) && empty($_POST['update_video'][0][1])){
            //参数为空就不裁剪
            $data['video_url']=$_POST['video_url1'];
        }else{
            //不为空就裁剪
            $status=$this->check_status($_POST['update_video'],$_POST['duration']);
            //删除这个判断的多余字段
            if($status['status']=="ok"){
                unset($status['status']);
//                var_dump($status);exit;
                $data_cut_merge=$this->cut_merge($_POST['video_url1'],$status);
//                var_dump($data_cut_merge);exit;
                if($data_cut_merge['status']=="ok"){
                    $data['video_url']=$data_cut_merge['video_url'];
                    //重新截取封面图
                    $ffmpeg = new FFmpeg(false);
                    $image_dir1=$this->upload_dir();
                    $true=$ffmpeg->getCoverFromVideo($data['video_url'],$image_dir1['uploadpath']);
                    $data['first_pic3']=$image_dir1['savehttp'];
                }else{
                    response(-1,$data_cut_merge);
                }
            }else{
                response(-1,$status);
            }
        }
////////////////////////////////////////////////////////////////////////////裁剪视频结束/////////////////////////////////////////////////////////////////////////////////////
        //先去精品视频表查询是否有这个ID的数据，有就两表联改，没有就改素材表
        $data1=$this->table->one("quality_video",['user_material_id'=>$_POST['id']]);
        //这是凭接修改数据
        if(!$data1){
            $data['join_type']=$_POST['fenlei'];
            $data['join_type_sub']=$_POST['huati'];
            $data['pic']=$_POST['video_url2'];
            $res=$this->table->update("user_material",$data,['id'=>$_POST['id']]);
            if($res){
                response(0,"修改成功");
            }else{
                response(-1,"修改失败");
            }
        }else{
            $data['join_type']=$_POST['fenlei'];
            $data['join_type_sub']=$_POST['huati'];
            $data['pic']=$_POST['video_url2'];
            $res=$this->table->update_edit($data,$_POST['id']);
            if($res){
                response(0,"修改成功");
            }else{
                response(-1,"修改失败");
            }
        }

    }

    /**
     * 检验裁剪参数是否正确
     */
    public function  check_status($data,$duration){
        if(!is_array($data)){
            return "裁剪参数不合法";
        }
        $arr=[];
        $arr1=[];
        foreach($data as $k=>$v){
            foreach($v as $kk=>$vv){
                //判断每个数都不是空的
                if(empty($vv) && $vv !=0){
                    return "裁剪数组不能为空";
                }
                //这里是判断填写的每个时间都是大于0的
                if($v[1]<0 || $v[0]<0){
                    return "裁剪所填时间不能小于0";
                }
                //判断后面一个数比前面一个数大
                if($v[1] < $v[0]){
                    return "裁剪前一个数小于后一个数";
                }
                //判断用户填写的最大值要小于视频时长
                if(ceil($duration) < $vv){
                    return "裁剪填写时间大于视频时长";
                }
            }
            //这里判断视频裁剪所得的总时长是否大于10，小于30
            $arr[]=$v[1]-$v[0];
            $arr1[]=$v[0];
        }
        //先统计裁剪时间的数组个数
        $length=count($arr);
        //只有一个数组值时直接判断
        if($length==1){
            if($arr[0]<10){
                return "裁剪视频时长不能小于10秒";
            }
            if($arr[0]>50){
                return "裁剪视频时长不能大于30秒";
            }
            $len1=strlen($arr1[0]);
            if($len1==1){
                $arr2[0]["start"]="00:00:0".$arr1[0];
            }else{
                $arr2[0]["start"]="00:00:".$arr1[0];
            }
            $ffmpeg = new FFmpeg(false);
            $arr2[0]["duration"]=$ffmpeg->formatFFmpegTime($arr[0]);
            $arr2["status"]="ok";
            return $arr2;
        }else{
            //不止一个时，先遍历数组
            $len=0;
            foreach($arr as $a=>$b){
                $len=$len+$b;
            }
            if($len>50){
                return "裁剪视频时长不能大于30秒";
            }
            if($len<10){
                return "裁剪视频时长不能小于10秒";
            }
            $arr2=[];
            $ffmpeg = new FFmpeg(false);
            foreach($arr1 as $g=>$h){
                $len2=strlen($h);
                if($len2==1){
                    $arr2[$g]["start"]="00:00:0".$h;
                }else{
                    $arr2[$g]["start"]="00:00:".$h;
                }
            }
            foreach($arr as $u=>$p){
                $arr2[$u]['duration']=$ffmpeg->formatFFmpegTime($p);
            }

            $arr2['status']="ok";
            return $arr2;
        }
    }

    /**
     * 视频裁剪与合并
     */
    public function cut_merge($video_url1,$status){
        $ffmpeg = new FFmpeg(false);
        //裁剪需要的临时路径
        $tmp_dir=$this->tmp_dir("video");

        //裁剪视频
        $cut_video_url=$ffmpeg->cutVideo($video_url1,$tmp_dir,$status);
        //判断是否裁剪成功
        if($cut_video_url){
            //合并视频重新存储的路径
            $upload_dir=$this->upload_dir("video",pathinfo($video_url1,PATHINFO_EXTENSION));
            //合并视频
            $ok=$ffmpeg->mergeTVideo($cut_video_url,$upload_dir['uploadpath'],false);
//            return $ok;
            //判断是否合并成功
            if($ok){
                $data['video_url']=$upload_dir['savehttp'];
                $data['status']="ok";
                return $data;
            }else{
                return "裁剪合并视频失败";
            }
        }else{
            return "裁剪失败";
        }
    }

    /**
     * 通过的数据重新推送
     */
    public function chongxin_tuisong(){
        $res=$this->table->chongxin_tuisong();
        $res1=[];
        foreach($res['row'] as $k=>$v){
            if(!empty($v['hengping_pic'])){
                $res1[]=$v;
            }
        }
        $len=count($res1);
        foreach($res1 as $kk=>$vv){
            $this->table->push($vv['id']);
            if($kk+1==$len){
                response(0,"成功",count($res1),$res1);
            }
        }

    }

}